import axios from 'axios';
import qs from 'query-string';
import { UserState } from '@/store/modules/user/types';

export interface LoginData {
  username: string;
  password: string;
  grant_type?: string;
  scope?: string;
  captcha_code?: string;
  captcha_key?: string;
}

export interface LoginRes {
  access_token: string;
}

export function login(data: LoginData) {
  const q: LoginData = { ...data, scope: 'all' };
  const param = qs.stringify(q);
  return axios.post<LoginRes>('/sys-auth/oauth/token', param);
}

// 也会401
export function logout() {
  return axios.delete<LoginRes>('/sys-auth/oauth/exit');
}

export function getUserInfo(userName: string) {
  return axios.get<UserState>('/cde-collaboration/user/userInfo', {
    params: {
      userName,
    },
  });
}

export interface UserParams {
  ids?: string;
  names?: string;
}

// 选人时通过userid/userName获取的成员列表
export function getUserList(params: UserParams) {
  return axios.get('/cde-collaboration/user/getUsers', {
    params,
  });
}

// 搜索用户
export function searchUser(
  searchValue: string,
  projectId: string | undefined = undefined
) {
  return axios.get('/cde-collaboration/user/search', {
    params: {
      searchValue,
      projectId,
    },
  });
}

export function getSms(phone: string) {
  return axios.get<string>('/sys-user/user/sms_captcha', {
    params: {
      phone,
    },
  });
}

// 激活用户
export function setUserPwd(id: string, pwd: string) {
  return axios.get<string>('/cde-collaboration/user/active', {
    params: {
      id,
      pwd,
    },
  });
}

export interface PasswordParams {
  captcha: string;
  key: string;
  phone: string;
  pwd: string;
}
// 忘记密码通过验证码修改密码
export function editPassword(data: PasswordParams) {
  return axios.put('/sys-user/user/password', data);
}

export interface PwdParams {
  oldPwd: string;
  newPwd: string;
  enterPwd?: string;
}
// 通过旧密码修改密码
export function modifyPassword(data: PwdParams) {
  return axios.put('/sys-user/user/pwd', data);
}

export interface PhoneParams {
  phone: string;
  captcha: string;
  key?: string;
}
// TODO: 更新手机号和邮箱需要改成cde自己的接口
// 更新用户手机号
export function updataPhone(data: PhoneParams) {
  return axios.put('/sys-user/user/change/phone', data);
}

// 更新手机号获取验证码
export function getPhoneCode(phone: string) {
  return axios.get('/sys-user/user/sms_change_phone_captcha', {
    params: {
      phone,
    },
  });
}

export interface EmailParams {
  userName?: string;
  id?: string;
  email: string;
}
// 更新用户邮箱
export function updateEmail(data: EmailParams) {
  return axios.put('/sys-user/user/information', data);
}

export function getThird(key: string) {
  return axios.get(`/sys-auth/oauth/render_url/${key}`);
}
